import socket
from datetime import datetime, timedelta
import threading

from APN1_2_1.fod.base_fod import build_bird


def get_start_time_from_user():
    """
    从用户输入获取开始时间的函数，格式要求为 'YYYY-MM-DD HH:MM:SS'
    """
    while True:
        try:
            input_time = input("请输入开始时间（格式为 'YYYY-MM-DD HH:MM:SS'）：")
            print(input_time)
            start_time = datetime.strptime(input_time, "%Y-%m-%d %H:%M:%S")
            return start_time
        except ValueError:
            print("输入的时间格式不正确，请重新输入！")


def format_fod_id(fod_id: int, len_fod_id: int = 5):
    __id = "0"
    fod_id = str(fod_id)
    __len_fod_id = len(fod_id)
    return __id * (len_fod_id - __len_fod_id) + fod_id


def client_connect():
    """
    客户端连接服务器并定时向服务端发送build_bird返回的内容的函数
    """
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ("192.168.227.60", 56001)
    client_socket.connect(server_address)
    print("已连接到服务器")

    start_time = get_start_time_from_user()
    current_time = start_time
    tag = 0
    send_num = 0

    def send_data():
        nonlocal current_time, tag, send_num
        # 将时间递增（这里以秒为单位，可根据需求调整时间变化粒度）
        current_time = (current_time + timedelta(seconds=1)).strftime("%Y%m%d%H%M%S")
        if tag % 1 == 0:
            send_num += 1
            fod_id = format_fod_id(send_num)
            data = build_bird(fod_id, current_time, current_time)
            client_socket.send(data.encode("utf-8"))
            print(f"已向服务器发送数据 {data}")
        current_time = datetime.strptime(current_time, "%Y%m%d%H%M%S")
        tag += 1
        # 每1秒启动一次新的定时器来执行发送数据的任务（可根据需求调整时间间隔）
        threading.Timer(30, send_data).start()

    # 启动第一次发送数据的定时器
    send_data()


if __name__ == "__main__":
    client_connect()
